package com.manor.paradise.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.text.*
import android.text.method.PasswordTransformationMethod
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.bumptech.glide.Glide
import com.lxj.xpopup.impl.FullScreenPopupView
import com.lxj.xpopup.interfaces.OnSelectListener
import com.manor.common.http.JHttpCallback
import com.manor.common.utils.ClickUtil
import com.manor.common.utils.GsonUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.utils.str
import com.manor.paradise.R
import com.manor.paradise.bean.NickNameBean
import com.manor.paradise.bean.PresenetBean
import com.manor.paradise.http.ElvesHttpConst
import com.manor.paradise.http.ElvesHttpUtil
import kotlinx.android.synthetic.main.dialog_friend_popup.view.*
import java.math.BigDecimal
import java.math.BigDecimal.*

/**
 * 转赠
 * @property presenetBean PresenetBean?
 * @constructor
 */
class PresentFriendsPopup(context: Context, private val listener: OnSelectListener) : FullScreenPopupView(context), View.OnClickListener {
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_friend_popup
    }

    internal var presenetBean: PresenetBean? = null
    var toId: String = ""
    override fun onCreate() {
        super.onCreate()
        im_dismiss.setOnClickListener(this)
        ed_password.inputType = InputType.TYPE_CLASS_NUMBER //输入类型
        ed_password.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(6)) //最大输入长度
        ed_password.transformationMethod = PasswordTransformationMethod.getInstance() //设置为密码输入框
        tvSdId.setOnClickListener { getToSdNum() }

        ed_sdId.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEND || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER) {
                when (event?.action) {
                    KeyEvent.ACTION_UP -> {
                        getToSdNum()
                        return@OnEditorActionListener true
                    }
                    else -> return@OnEditorActionListener true
                }
            }
            false
        })


        ed_FreeQuantity.addTextChangedListener(object : TextWatcher {
            @SuppressLint("SetTextI18n")
            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(ed_FreeQuantity.text.toString())) {
                    presenetBean?.run {
                        var sxf = BigDecimal("1").subtract(serviceRate)

                        val real = BigDecimal(ed_FreeQuantity.text.toString())
                                .divide(sxf, 4, BigDecimal.ROUND_DOWN)

                        ed_deduction.text = real.toString()
//                        ed_deduction.text = BigDecimal(ed_FreeQuantity.text.toString())
//                                .multiply(sxf)
//                                .setScale(2, BigDecimal.ROUND_DOWN)
//                                .toString()
                        val sun: BigDecimal = BigDecimal(ed_FreeQuantity.str()).multiply(dayAvg)
                        if (sun > ZERO)
                            sun.setScale(2, BigDecimal.ROUND_DOWN)


                        tv_jz.text = sun.toString() + "劵"
                        tv_z_tip.text = "${ed_deduction.str()} x $sxf = ${ed_FreeQuantity.str()}"
                    }
                } else {
                    tv_z_tip.text = "实扣数量x(1-服务费率)=实到米粒"
                    ed_deduction.text = "0"
                    tv_jz.text = ""
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
        tv_confirm.setOnClickListener {

            if (!TextUtils.isEmpty(toId) && !TextUtils.isEmpty(ed_password.text.toString()) && !TextUtils.isEmpty(ed_deduction.text.toString()) && ed_password.text.toString().length == 6) {
                tv_confirm.isEnabled = false
                ElvesHttpUtil.getIncrease(BigDecimal(ed_FreeQuantity.text.toString()), ed_password.text.toString(), toId, object : JHttpCallback() {
                    override fun onSuccess(code: Int, msg: String, info: String) {
                        ToastUtil.show(msg)
                        if (code != 200) {
                            tv_confirm.isEnabled = true
                            return
                        }
                        listener.onSelect(0, "")
                        dismiss()

                    }

                    override fun onError() {
                        super.onError()
                        tv_confirm.isEnabled = true
                    }

                })
            } else {
                if (TextUtils.isEmpty(ed_sdId.text.toString())) {
                    ToastUtil.show("请输接收对方淘米号")
                    return@setOnClickListener
                }
                if (toId == "") {
                    ToastUtil.show("未找到此用户")
                    return@setOnClickListener
                }
                if (ed_password.text.toString().length < 6) {
                    ToastUtil.show("请输入6位交易密码")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(ed_password.text.toString())) {
                    ToastUtil.show("请输入交易密码")
                    return@setOnClickListener
                }
                if (TextUtils.isEmpty(ed_deduction.text.toString())) {
                    ToastUtil.show("请输入转赠数量")
                    return@setOnClickListener
                }

            }
        }
        tv_confirm.isEnabled = false
        ElvesHttpUtil.getAvgpiceInfo(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                tv_confirm.isEnabled = true
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                presenetBean = GsonUtil.gsonToBean(info, PresenetBean::class.java)
                presenetBean?.run {
                    tv_jksl.text = crystalOre.toString()
                    tv_jj.text = dayAvg.toString() + "券/米粒"
                    ed_poundage.text = "${serviceRate.multiply(BigDecimal(100))}%"
                }


            }

            override fun onError() {
                super.onError()
                tv_confirm.isEnabled = true
            }

        })

    }

    private fun getToSdNum() {
        if (!TextUtils.isEmpty(ed_sdId.text.toString())) {
            if (ed_sdId.text.toString().length > 5) {
                toId = ""
                tv_name.text = ""
                ElvesHttpUtil.getSearchNo(ed_sdId.text.toString(), object : JHttpCallback() {
                    override fun onSuccess(code: Int, msg: String, info: String) {
                        if (code != 200) {
                            tv_name.text = msg
                            toId = ""
                            //   ToastUtil.show(msg)
                            return
                        }
                        var nick: NickNameBean = GsonUtil.gsonToBean(info, NickNameBean::class.java)
                        tv_name.text = nick.nickName.toString()
                        toId = nick.uid.toString()
                    }

                    override fun onError() {
                        super.onError()
                        tv_name.text = "没找到用户"
                        toId = ""
                    }
                })
            } else {
                ToastUtil.show("淘米号输入不正确")
                tv_name.text = ""
            }
        }

    }


    override fun onClick(v: View?) {
        if (ClickUtil.canClick(500))
            when (v?.id) {
                R.id.im_dismiss -> {
                    dismiss()
                }
            }
    }

    override fun onDestroy() {
        Glide.get(context).clearMemory()

        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_SHOP_BY_DEAL)
        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_SHOP_BY_INFO)
        super.onDestroy()
    }
}